<script lang="ts" setup>
import type { AiPromptTemplatesApi } from '#/api/ai/prompt/promptTemplates';

import { ref } from 'vue';

import { useVbenDrawer } from '@vben/common-ui';
import { IconifyIcon } from '@vben/icons';

import { DownOutlined } from '@ant-design/icons-vue';
import { useClipboard } from '@vueuse/core';
import { Button, Card, Dropdown, Menu, message, Spin } from 'ant-design-vue';

import { getPromptTemplates } from '#/api/ai/prompt/promptTemplates';
import { getPromptVersionNumList } from '#/api/ai/prompt/promptVersions';
import DynamicForm from '#/components/dynamic-form/index.vue';
import { Image } from '#/components/image';
import { MarkdownView } from '#/components/markdown-view';

const formData = ref<AiPromptTemplatesApi.PromptTemplates>();
const { copy } = useClipboard({ legacy: true }); // 初始化 copy 到粘贴板，启用兼容模式
const isCopying = ref(false); // 复制状态
const versionNumList = ref([]);
const variablesList = ref([]);
const loading = ref(false);
const versionNumAll = ref('');

async function copyContent(content: string) {
  if (isCopying.value) return; // 防止重复点击

  try {
    if (!content) {
      message.warning('没有可复制的内容');
      return;
    }

    isCopying.value = true;
    await copy(content);
    message.success('复制成功！');
  } catch (error) {
    message.error('复制失败，请重试');
    console.error('复制失败:', error);

    // 降级方案：使用传统的execCommand方法
    try {
      const textarea = document.createElement('textarea');
      textarea.value = content;
      textarea.style.position = 'fixed';
      textarea.style.opacity = '0';
      textarea.style.left = '-9999px';
      textarea.style.top = '-9999px';
      document.body.append(textarea);

      textarea.focus();
      textarea.select();

      const successful = document.execCommand('copy');
      textarea.remove();

      if (successful) {
        message.success('复制成功！');
      } else {
        message.error('复制失败，请手动复制');
      }
    } catch (fallbackError) {
      message.error('复制失败，请手动复制');
      console.error('降级复制失败:', fallbackError);
    }
  } finally {
    isCopying.value = false;
  }
}
const [Drawer, drawerApi] = useVbenDrawer({
  async onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      formData.value = undefined;
      return;
    }
    let data = drawerApi.getData<AiPromptTemplatesApi.PromptTemplates>();
    if (!data || !data.id) {
      return;
    }
    drawerApi.lock();
    try {
      data = await getPromptTemplates(data.id, '');
      formData.value = data;
      versionNumAll.value = formData.value?.versionNum; // 获取最新的版本号
      variablesList.value = data.variablesList;
      getVersionNumList(data.id);
    } finally {
      drawerApi.unlock();
    }
  },
});
function getVersionNumList(id: number) {
  getPromptVersionNumList(id).then((res) => {
    versionNumList.value = res || [];
  });
}

const changeForm = async (e: { key: string }) => {
  const versionNum = e.key;
  if (!versionNum) return;

  loading.value = true; // 开始加载动画

  try {
    const data = drawerApi.getData<AiPromptTemplatesApi.PromptTemplates>();

    const newData = await getPromptTemplates(data.id, versionNum);

    formData.value = newData;
    variablesList.value = newData.variablesList;
    getVersionNumList(newData.id);

    drawerApi.setData({
      ...newData,
      versionNum: newData.versionNum,
    });
  } catch (error) {
    console.error('切换版本失败:', error);
  } finally {
    loading.value = false; // 加载结束
  }
};
const handleSubmit = () => {
  console.log('formData', formData.value);
};
</script>

<template>
  <Drawer
    :title="`${formData?.name || '提示词模版详情'}(${
      formData?.code || '未指定'
    })`"
    class="w-[80%]"
    :show-cancel-button="false"
    :show-confirm-button="false"
  >
    <template #extra>
      使用次数：{{ formData?.usageCount || 0 }} 收藏次数：{{
        formData?.collect || 0
      }}
      评分：{{ formData?.rating || 0 }}
    </template>
    <!-- 基本信息 -->
    <Card class="mb-4" title="基本信息">
      <div class="grid grid-cols-2 gap-4 text-sm">
        <div>
          <span class="text-gray-500">分类：</span>
          <span class="text-gray-500">{{
            formData?.categoryName || '未分类'
          }}</span>
        </div>
        <Spin :spinning="loading" tip="正在切换版本...">
          <div class="flex items-center">
            <span class="text-gray-500">版本：</span>
            <span class="mr-2 text-gray-500">{{ formData?.versionNum }}</span>
            <Dropdown>
              <template #overlay>
                <Menu @click="changeForm">
                  <Menu.Item
                    v-if="versionNumAll !== formData?.versionNum"
                    :key="versionNumAll"
                  >
                    当前版本（{{ versionNumAll }}）
                  </Menu.Item>

                  <Menu.Divider v-if="versionNumAll !== formData?.versionNum" />

                  <!-- 历史版本列表 -->
                  <Menu.Item
                    v-for="item in versionNumList"
                    :key="item.versionNum"
                  >
                    {{ item.versionNum }}
                  </Menu.Item>
                </Menu>
              </template>
              <Button type="primary" size="small">
                历史版本
                <DownOutlined />
              </Button>
            </Dropdown>
          </div>
        </Spin>

        <div>
          <span class="text-gray-500">语言：</span>
          <span class="text-gray-500">{{ formData?.language }}</span>
        </div>
        <div>
          <span class="text-gray-500">可见性：</span>
          <span class="text-gray-500">{{
            formData?.visibility === 1 ? '公开' : '私有'
          }}</span>
        </div>
        <div
          class="col-span-2"
          v-if="formData?.modelTypeName && formData.modelTypeName.length > 0"
        >
          <div class="flex items-center gap-2">
            <span class="text-gray-500">适用模型：</span>
            <div class="flex flex-wrap gap-2">
              <span
                v-for="model in formData.modelTypeName"
                :key="model"
                class="rounded-full bg-blue-100 px-2 py-1 text-xs text-blue-500"
              >
                {{ model }}
              </span>
            </div>
          </div>
        </div>
        <div
          class="col-span-2"
          v-if="formData?.tagList && formData.tagList.length > 0"
        >
          <div class="flex items-center gap-2">
            <span class="text-gray-500">标签：</span>
            <div class="flex flex-wrap gap-2">
              <span
                v-for="tag in formData.tagList"
                :key="tag"
                class="rounded-full bg-green-100 px-2 py-1 text-xs text-green-500"
              >
                {{ tag }}
              </span>
            </div>
          </div>
        </div>
      </div>
    </Card>
    <Card class="mb-4" title="提示词内容">
      <template #extra>
        <Button
          class="flex items-center bg-transparent px-1.5 hover:bg-gray-100"
          type="text"
          color="primary"
          :loading="isCopying"
          @click="copyContent(formData?.content || '')"
        >
          <IconifyIcon icon="lucide:copy" /> 复制
        </Button>
      </template>
      <MarkdownView
        v-if="formData?.content"
        class="text-sm text-gray-600"
        :content="formData?.content"
      />
    </Card>

    <!-- 提示词变量 -->
    <Card
      v-if="variablesList && variablesList.length > 0"
      class="mb-4"
      title="提示词变量"
    >
      <DynamicForm :list="variablesList" @submit="handleSubmit" />
    </Card>

    <Card class="mb-4" title="使用说明">
      <div
        v-if="formData?.usageDescription"
        class="whitespace-pre-wrap text-sm leading-relaxed text-gray-600"
      >
        {{ formData.usageDescription }}
      </div>
      <div v-else class="text-sm italic text-gray-400">暂无使用说明</div>
    </Card>

    <!-- 提示词描述 -->
    <Card v-if="formData?.description" class="mb-4" title="提示词描述">
      <div class="whitespace-pre-wrap text-sm leading-relaxed text-gray-600">
        {{ formData.description }}
      </div>
    </Card>

    <!-- 其他参数 -->
    <Card class="mb-4" title="效果展示">
      <Image
        :src="formData?.effectImg"
        :width="200"
        :list-flag="true"
        :height="200"
      />
    </Card>
  </Drawer>
</template>
